package com.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import com.fgsort.FileArrayProvider;

public class PlcSrc {

	///get plc source
    static public List<String> getPlcSrc(String sPlcSrcFile) throws IOException {

    	List<String> lstPlcSrc = new ArrayList<String>();
    	FileArrayProvider fap = new FileArrayProvider();

    	///read plc src file
    	String[] lines = fap.readLines(sPlcSrcFile);
	
    	///finds valid function groups and stores in array
        for (String line : lines) {
        	lstPlcSrc.add(line);
		}

        return lstPlcSrc;
    }	
	
    ///get inputs/outputs from plc source
    static public ArrayList<String> getIO(List<String> lstPlcSrc) {

    	List<String> lstIOtmp = new ArrayList<String>();
    	Pattern pBool = Pattern.compile("(I|Q)\\s+\\d+\\.\\d.*");
    	Pattern pByteWord = Pattern.compile("(IB|QB|IW|QW)\\s+\\d+");
    	
    	for (String line : lstPlcSrc)	{
    		Matcher mBool = pBool.matcher(line);
    		Matcher mByteWord = pByteWord.matcher(line);
    		if (mBool.find()) {
    			String str = mBool.group();  
    			lstIOtmp.add(str);
    		}
    		else {
    			if (mByteWord.find())	{
        			String str = mByteWord.group();  
        			lstIOtmp.add(str);
    			}
    		}
    	}

        ///create a HashSet which allows no duplicates
        HashSet<String> hashSet = new HashSet<String>(lstIOtmp);

        ///assign the HashSet to a new ArrayList
        ArrayList<String> lstIO = new ArrayList<String>(hashSet);
        
        ///sort list in ascending order
        Collections.sort(lstIO);
    	
        return lstIO;    	
    }
}
